{% extends 'admin.phtml' %}

{% block head %}
{% autoescape false %}
{{ js('/js/knockout.validation.min.v0.9.js') }}
{% endautoescape %}
{% endblock %}

{% block title %}Управление рубриками{% endblock %}

{% block body %}

<div class="row" data-bind="with: list">
    <div class="span8">
        {#<div class="well">
            <a class="btn btn-primary" data-bind="click: $root.add"><i class="icon-plus icon-white"></i> Добавить</a>
        </div>#}
        <table class="table table-condensed">
            <thead>
                <tr>
                    <th>Название</th>
                    <th>URL</th>
                    <th>Статей</th>
                    <th>&nbsp;</th>
                </tr>
            </thead>
            <tbody data-bind="foreach: $data">
                <tr>
                    <td><span data-bind="text: title, style: {margin: '0 0 0 ' + (level * 30) + 'px'}"></span></td>
                    <td data-bind="text: splitUrl(url).value" class="muted"></td>
                    <td data-bind="text: articles_count == '0' ? '' : articles_count" class="muted"></td>
                    <td>
                        <div class="btn-group">
                            <a href="#" data-bind="click: $root.edit" class="btn btn-small btn-info" title="Редактировать"><i class="icon-pencil icon-white"></i></a>
                            <a href="#" data-bind="click: $root.add" class="btn btn-small btn" title="Добавить подрубрику"><i class="icon-plus"></i></a>
                            <a href="#" data-bind="click: $root.moveUp, css: {disabled: !$root.canMoveUp($data)}" class="btn btn-small btn" title="Переместить вверх"><i class="icon-chevron-up"></i></a>
                            <a href="#" data-bind="click: $root.moveDown, css: {disabled: !$root.canMoveDown($data)}" class="btn btn-small btn" title="Переместить вниз"><i class="icon-chevron-down"></i></a>
                            <a href="#" data-bind="click: $root.gotoArticlesList" class="btn btn-small btn" title="Перейти к списку статей"><i class="icon-list"></i></a>
                            <a href="#" data-bind="click: $root.remove, css: {disabled: !$root.canRemove($data)}" class="btn btn-small" title="Удалить"><i class="icon-remove"></i></a>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>    

    </div>
</div>

<div class="row" data-bind="with: single">
    <div class="span8">
        <form class="form-horizontal" data-bind="submit: $root.save" method="post">
            <fieldset>
                <legend data-bind="text: $root.legend"></legend>

                {# title #}				
                <div class="control-group" data-bind="css: {error : !title.isValid() && title.isModified()}">
                    <label class="control-label" for="title">Название</label>
                    <div class="controls">
                        <input id="title" type="text" data-bind="value: title" />
                    </div>
                </div>

                {# url #}				
                <div class="control-group" data-bind="css: {error : !url_value.isValid() && url_value.isModified()}">
                    <label class="control-label" for="url_value">URL</label>
                    <div class="controls">
                        <div class="input-prepend">
                            <span class="add-on" data-bind="text: url_prefix + '/'"></span>
                            <input id="url_value" type="text" data-bind="value: url_value" class="input-small" />
                        </div>
                    </div>
                </div>

                {# template #}
                <div class="control-group" data-bind="css: {error : !template.isValid() && template.isModified()}">
                    <label class="control-label" for="category">Шаблон</label>
                    <div class="controls">
                        <select id="category" data-bind="value: template, options: $root.templates, optionsText: 'title', optionsValue: 'id', optionsCaption: '-- выберите шаблон --'"></select>
                    </div>

                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">Сохранить</button>
                        <button type="reset" class="btn" data-bind="click: $root.cancel">Отмена</button>
                    </div>
                </div>
            </fieldset>
        </form>
    </div>
</div>

<div class="loadingIndicator">Загрузка...</div>

{% autoescape false %}
<script type="text/javascript">

    ko.validation.init({
        errorMessageClass: 'help-inline'
    })
   
    function splitUrl(url) {
        var parts = url.split('/')
        if (parts.length > 1) {
            var value = parts.pop()
            return {prefix: parts.join('/'), value: value}
        }
        return {prefix: '', value: url}
    }
   
    ko.validation.rules.required.message = 'обязательное поле'

    var Category = function(data) {
        var self = this
        self.id = data.id
        self.parent = data.parent
        self.template = ko.observable(data.template).extend({required: true})
        self.title = ko.observable(data.title).extend({required: true})
        self.url_prefix = splitUrl(data.url).prefix
        self.url_value = ko.observable( splitUrl(data.url).value ).extend({required: true})
        self.url = ko.computed(function() {
            return self.url_prefix
                ? self.url_prefix + '/' + self.url_value()
            : self.url_value()
        })
    }

    var CategoriesModel = function() {
        var self = this
        
        self.loadList = function(callback) {
            $.getJSON('/admin/categories/list', callback)
        }
        
        self.loadSingle = function(id, callback) {
            $.getJSON('/admin/categories/single', {id: id}, function(data){
                callback(data)
            })
        }
        
        self.save = function(data, callback) {
            $.post('/admin/categories/save', {data: data}, callback)
        }
        
        self.remove = function (id, callback) {
            $.post('/admin/categories/remove', {id: id}, callback)
        }
        
        self.move = function(id, direction, callback) {
            $.get('/admin/categories/move', {id: id, direction: direction}, callback)
        }
    }

    var CategoriesViewModel = function(model) {
        var self = this
        
        self.model = model
        
        self.list = ko.observable()
        self.single = ko.observable()
        self.legend = ko.observable()
        
        self.templates = [
            {id: 'single', title: 'Single'},
            {id: 'list', title: 'List'},
            {id: 'splash', title: 'Splash'},
        ]
		
        self.edit = function(item) {
            self.legend('Редактирование рубрики')
            location.hash = '/edit/' + item.id
        }

        self.add = function(item) {
            self.legend('Создание рубрики')
            location.hash = '/add/' + item.id
        }

        self.canRemove = function(c) {
            return c.has_children == '0' && c.articles_count == '0' && +c.id > 1;
        }
		
        self.remove = function(item) {
            if (self.canRemove(item) && confirm('Вы уверены, что хотите удалить запись?')) {
                self.model.remove(item.id, self.loadList)
            }
        }

        self.cancel = function() {
            location.hash = '/list'
        }
        
        self.canMoveUp = function(item) {
            return item.can_move_up == '1';
        }
        
        self.moveUp = function(item) {
            if (self.canMoveUp(item)) {
                self.model.move(item.id, 'up', self.loadList)
            }
        }

        self.canMoveDown = function(item) {
            return item.can_move_down == '1';
        }

        self.moveDown = function(item) {
            if (self.canMoveDown(item)) {
                self.model.move(item.id, 'down', self.loadList)
            }
        }
        
        self.handleList = function() {
            self.single(null)
            self.loadList()
        }
        
        self.handleEdit = function() {
            var id = this.params.id
            self.list(null)
            self.model.loadSingle(id, function(data){
                self.single(new Category(data))
            })
        }
        
        self.handleAdd = function() {
            self.list(null)
            var pid = this.params.pid
            self.model.loadSingle(pid, function(parent) {
                self.single(new Category({id: -1, title: '', url: parent.url + '/', parent: parent.id}))
            })
        }
        
        self.save = function() {
            var errors = ko.validation.group(self.single())
            if (errors().length == 0) {
                model.save(self.single(), function() {
                    location.hash = '/list'
                })
            } else {
                errors.showAllMessages()
            }
        }

        self.loadList = function() {
            self.model.loadList(self.list)
        }

        self.gotoArticlesList = function(item) {
            location.href = '/admin/articles#/category/' + item.id;
        }

        Sammy(function() {
            this.get('#/list', self.handleList)
            this.get('#/edit/:id', self.handleEdit)
            this.get('#/add/:pid', self.handleAdd)
        }).run('#/list')
    }
    
    var model = new CategoriesModel()
    var viewModel = new CategoriesViewModel(model)
    ko.applyBindings(viewModel)
    
</script>
{% endautoescape %}
{% endblock %}
